package icu.lookyousmileface.netty.simple.groupchat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @author shenj
 * @title: GroupClient
 * @projectName NettyPro
 * @date 2020/12/7 15:17
 */
public class GroupClient {

    private  String ip;
    private  int port;
    private static final EventLoopGroup workerLoop = new NioEventLoopGroup();
    private static final Bootstrap startApplicationClient =  new Bootstrap();

    public  GroupClient(String ipIn, int portIn){

        this.ip = ipIn;
        this.port = portIn;
    }

    public void run() throws InterruptedException {
        try {
            startApplicationClient.group(workerLoop)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {

                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("stringDecoder", new StringDecoder());
                            pipeline.addLast("stringEncoder", new StringEncoder());
                            pipeline.addLast("ClientHandler", new SimpleChannelInboundHandler<String>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                    System.out.println(msg.trim());
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                    ctx.close();
                                }
                            });

                        }
                    });

            ChannelFuture channelFuture = startApplicationClient.connect(ip, port).sync();
            Channel channel = channelFuture.channel();
            System.out.println("------------"+channel.remoteAddress()+"------------");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()){
                String msg = scanner.next();
                channel.writeAndFlush(msg+"\r\n");
            }

        }finally {
            workerLoop.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
        new GroupClient("127.0.0.1", 8881).run();
    }
}
